// 运行多个服务
package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"golang.org/x/sync/errgroup"
	"net/http"
	"time"
)

var g errgroup.Group

func runMultipleServer() {
	//服务器1：
	server01 := &http.Server{
		Addr:         ":8081",
		Handler:      router01(),
		ReadTimeout:  5 * time.Second,  //读取超时时间
		WriteTimeout: 10 * time.Second, //写入超时时间
	}
	//服务器2：
	server02 := &http.Server{
		Addr:         ":8082",
		Handler:      router02(),
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 10 * time.Second,
	}
	//开启服务
	g.Go(func() error { //开启服务器程序1
		return server01.ListenAndServe()
	})
	g.Go(func() error { //开启服务器程序2
		return server02.ListenAndServe()
	})
	//让监听程序一直处于等待状态
	if err := g.Wait(); err != nil {
		fmt.Println("执行失败：", err)
	}
}

func router01() http.Handler {
	r1 := gin.Default()
	r1.GET("/", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusOK,
			"msg":  "服务器01的响应",
		},
		)
	})
	return r1
}

func router02() http.Handler {
	r1 := gin.Default()
	r1.GET("/", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusOK,
			"msg":  "服务器02的响应",
		},
		)
	})
	return r1
}

//解决包：golang.org/x/sync/errgroup 无法 go get的问题
// cd $GOPATH/src/golang.org/x
// git clone https://github.com/golang/sync.git
// git clone https://github.com/golang/crypto.git
// git clone https://github.com/golang/sys.git
